<?php
require('conf.php');

class Xnu
{
	private $apiKey;
	private $op;
	private $alias;
	private $gw;
	
	public function __construct()
	{
		$this->gw=new httpGateWay(__XNU_URL__);
		$this->setApiKey(__XNU_APIKEY__);
	}
	
	
	public function setApiKey($apiKey)
	{
		if(!is_string($apiKey) || $apiKey=='' )
			throw new Exception('Apikey cannot be empty.Please set an apikey in you conf.php file');
			
		$this->apiKey=$apiKey;
	}
	
	
	public function nu($url,$alias='')
	{
		if($alias)
		{
			$this->gw->addParamValue('op','ca');
			$this->gw->addParamValue('alias',$alias);
		}
		else $this->gw->addParamValue('op','cc');
		
		$this->gw->addParamValue('apikey',$this->apiKey);
		$this->gw->addParamValue('url',$url);
		
		
		return $this->gw->query();
	}	
}


class httpGateWay
{

	private $query;
	private $url;
	private $lastError;
	
	
	public function __construct($url='')
	{
		$this->query=array();
		$this->url=$url;
	}
	
	
	public function addParamValue($param,$value)
	{
		$this->query[$param]=urlencode($value);
	}

	
	public function query()
	{
		$ch = curl_init();
		$options=array(
			CURLOPT_HEADER => 0,
			CURLOPT_URL => $this->url.'?'.http_build_query($this->query),
			CURLOPT_FRESH_CONNECT => 1,
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_TIMEOUT => 5,
		);
		curl_setopt_array($ch,$options); 
		$result=curl_exec($ch);
		$error=curl_errno($ch);
		
		if($error>0)
		{
			$error=curl_error($ch);
			curl_close($ch);
			return $error;
		}
		curl_close($ch);
		return $result;
	}
	
}
?>